package org.ccay.validator.validators;

import org.ccay.core.util.StringUtil;
import org.ccay.validator.ValidatorSystemException;
import com.opensymphony.xwork2.validator.ValidationException;

/**
 * 使用示例
 *  <field name="userAccount">
 *  <field-validator type="lengthLimit">
 *     <param name="notInLength">6,8,9,11</param> //注意：只能是“,”分隔的数字字符串
 *     <message key="ccay.security.validate.userAccountError">userAccount length can not be 6,8,9,or 11.</message>
 *  </field-validator>
 *  </field>
 */

/**
 * 字符串长度验证
 * 
 * 
 * @since 2012-6-27
 */
public class LengthLimitValidator extends AbstractFieldValidator {

	private String notInLength; // "," 分割的字符串， 如 6,8,9,11

	public String getNotInLength() {
		return notInLength;
	}

	public void setNotInLength(String notInLength) {
		this.notInLength = notInLength;
	}

	public void validate(Object object) throws ValidationException,
			ValidatorSystemException {
		// 获取验证属性名称
		String fieldName = getFieldName();
		// 获取当前属性的value
		String fieldValue = (String) getFieldValue(fieldName, object);
		// 获取utf8的长度
		int length;
		// 如果为空 就不校验
		if (nullValue(fieldValue)) {
			return;
		}

		// 获取utf8的长度
		length = StringUtil.getUTF8Length(fieldValue);
		// 如果等于某长度 那么把验证信息加入错误信息中
		String[] stringArray = notInLength.split(",");
		for (int i = 0; i < stringArray.length; i++) {
			if (length == Integer.parseInt(stringArray[i])) {
				addFieldError(fieldName, object);
			}
		}
	}

	//fieldValue为空的判断
	private boolean nullValue(String fieldValue) {
		return (fieldValue == null || fieldValue.trim().equals("")) 
			|| (notInLength == null || notInLength.trim().equals(""));
	}
}
